package com.luli.config.websocketConfig;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * 陆离
 * ws://127.0.0.1:8088/LuLi/websocket/1
 * https://blog.csdn.net/weixin_60713320/article/details/134285482?ops_request_misc=&request_id=&biz_id=102&utm_term=java%E4%BD%BF%E7%94%A8websocket&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-5-134285482.nonecase&spm=1018.2226.3001.4187
 * 2024/5/31 10:53:07
 */
@Slf4j
@ServerEndpoint(value = "/websocketPojo/{userId}")
@Component
public class WebSocketEndpoint {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收的用户id
     */
    private String userId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
      SessionPool.sessions.put(userId,session);

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        SessionPool.close(session.getId());
        session.close();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        SessionPool.senMessage(message);
    }

    /**
     * @param error 错误
     */
    @OnError
    public void onError( Throwable error) {
        log.error("发生错误", error);
    }

    /**
     * 发送消息
     * @param message 消息
     * @throws IOException 异常
     */
    public void sendMessage(String message) throws IOException {
        for (String sessionId : SessionPool.sessions.keySet()) {
          SessionPool.sessions.get(sessionId).getAsyncRemote().sendText(message);
        }
    }


}
